package com.powerhua.privilege.web.action;

import com.powerhua.core.utils.CommonUtils;
import java.util.List;

import javax.servlet.ServletRequest;

import com.powerhua.privilege.PrivilegeUtils;
import com.powerhua.privilege.domain.Group;
import com.powerhua.privilege.web.action.convert.GroupConverter;
import com.powerhua.support.web.HtmlBeanConverter;

public class GroupAction implements ActionInterface {

	public String doAction(ServletRequest map) {
		// get from html
		String action = CommonUtils.getStringFromReq(map, PrivilegeUtils
                .getPermissionParamProperty("Param.Action"));
		Group group = (Group)HtmlBeanConverter.getBeanFromHtml(Group.class, map);
		
		// result
		String result = "";
		
		// action
		if(action.equals(PrivilegeUtils
                .getPermissionParamProperty("Action.Info"))) {
			Group groupFromDb = getInfo(group);
			result = GroupConverter.getInfoScriptStr(groupFromDb);
		} else if(action.equals(PrivilegeUtils
                .getPermissionParamProperty("Action.List"))) {
			String start = CommonUtils.getStringFromReq(map, PrivilegeUtils
                    .getPermissionParamProperty("Param.Start"));
			String offset = CommonUtils.getStringFromReq(map, PrivilegeUtils
                    .getPermissionParamProperty("Param.Offset"));
			List list = getList(start, offset);
			result = GroupConverter.getListScriptStr(list);
		}
		
		return result;
	}
	
	private Group getInfo(Group group) {
		List list = PrivilegeUtils.getGroupManager().findGroups(group, 0, 0);
		if(!(list.size() == 1)) {
			return null;
		} else {
			return (Group)list.get(0);
		}
	}
	
	private List getList(String start, String offset) {
		int intStart = Integer.parseInt(start);
		int intOffset = Integer.parseInt(offset);
		List list = PrivilegeUtils.getGroupManager().findGroups(null, intStart, intOffset);
		return list;
	}

}
